import sqlite3
from teambition import create_task
from record_log import record_log


def write_back_tb():
    # 连接到 SQLite 数据库
    conn = sqlite3.connect('/home/xc/zy/sales_top3_project/top3_sales_processing/local_daily_report.db')
    cursor = conn.cursor()

    try:
        # 读取 tops_question 表中的数据
        cursor.execute("SELECT DBCTEXTAREA1, CREATEDBY, DEPARTNAME FROM tops_question")
        rows = cursor.fetchall()
        
        if rows:
            # 遍历每一行，处理数据
            for row in rows:
                title_content = row[0]  # DBCTEXTAREA1 赋值给 content
                creator = row[1]  # CREATEDBY 赋值给 creator
                departName = row[2]
                note = title_content
                # 判断 content 是否大于 500 字符
                if len(title_content) >= 500:
                    content = title_content[:498]  # 截取前 498 字符
                else:
                    content = title_content
                print(f"Content: {content}, Creator: {creator},departName: {departName}")
                create_task(content, creator, departName,note) 
        else:
            print('没有筛选出有效的top3问题')
            record_log('没有筛选出有效的top3问题',"info")
            
        

    except sqlite3.Error as e:
        print(f"An error occurred: {e}")

    finally:
        # 关闭数据库连接
        cursor.close()
        conn.close()


if __name__ == '__main__':
    write_back_tb()
